/**
 * 商品模块
 */
define(function(require, exports, module) {
	"require:nomunge,exports:nomunge,module:nomunge";

	var merchandiseTypeId="",merchandiseName="",sort="0",pageSize=24;
	
	var validate = require("../../custom/base/component-validate.js");
	
	require("../../custom/base/component-core.js");
	
	var base = require("../../custom/base/component-base.js");
	
	base.init(base);
	
	var async = require("../../custom/base/component-async.js");
	
	require("../../custom/base/component-md5.js");
	
	
	//初始化函数
	exports.init=function(m){
		
		window.$ldh_merchandise=m;
		
		base.setFromPage("");
		
		exports.getMerchandiseDetail(base.getParameter("merchandiseId"));
		
				
	};
	

	//查询商品详细信息
	var detail,minAmount=0;
	exports.getMerchandiseDetail=function(merchandiseId){
		
		base.showLoading();
		var params = {
				userId:base.getCookie("userId"),
				merchandiseId:merchandiseId,
				sign:MD5(merchandiseId)
				
		};
		detail="";
		
		eval(
				Wind.compile("async", function() {

					var data = $await(async.DDF_AsyncRequest("POST", ctx+"/shopapp/Goods/queryDetails.do", params));

					
							if(data["code"]==1){
								
								var htmlStr="";
								
								minAmount=data["details"]["minAmount"];
										htmlStr += '<li><h3>'+data["details"]["merchandiseName"]+'</h3></li>';
										if(data["details"]["price"]<data["details"]["mktprice"]){
											htmlStr += '<li><span>价格：</span><strong><em id="price">'+data["details"]["price"]+'</em>元</strong><s>'+data["details"]["mktprice"]+'元</s></li>';
										}else{
											htmlStr += '<li><span>价格：</span><strong><em id="price">'+data["details"]["price"]+'</em>元</strong></li>';
										}
										htmlStr += '<li><span>购买数量：</span><div class="store_goods_addsub" id="'+data["details"]["merchandiseId"]+'">';
										htmlStr += '<button class="btn_sub" style="display:none;" data-role="button" data-theme="b"  onclick=$ldh_merchandise.subCartNum("'+data["details"]["merchandiseId"]+'","'+data["details"]["price"].toFixed(2)+'")>-</button>';
										htmlStr += '<span style="display:none;" id="num">0</span>';
										htmlStr += '<button  class="btn_add" data-role="button" data-theme="b" onclick=$ldh_merchandise.addCartNum("","'+data["details"]["merchandiseId"]+'","'+data["details"]["price"].toFixed(2)+'")>+</button>';
										htmlStr += '</div>';
										htmlStr += '</li>';
										htmlStr += '<li>产品介绍：'+data["details"]["brief"]+'</li>';
								
								$("#ldhGoods .goods_info ul").html(htmlStr);
								
								//$("#ldhGoods .goods_more_info").html(data["details"]["detail"]);
								detail=data["details"]["detail"];
								//$("#ldhGoods .goods_btm em").html(data["cartNums"]);
								
								$("#ldhGoods .mine_link li").html('<a data-transition="none" rel="external"  href="'+ctx+'/h5/shopIndex/'+data["details"]["shopId"]+'.shtml" class="ui-link"><i><img src="'+ctx+'/v1/h5/img/icon_store.png"></i><span>进入店铺</span></a>');
								
								htmlStr="";
								for(var i=0;i<data["images"].length;i++){
									htmlStr+='<div class="mod_02"><a data-transition="none" href="#"><img src="'+fileOpenSourceUrl+data["images"][i]["imgUrl"]+'" alt=""></a></div>';
								}
								$("#ldhGoods .goods_pic .slide_02").html(htmlStr);
								
								if ($(".banner_scroll").width()){
									   winWidth = $(".banner_scroll").width()-20;
								}
								
								$("#slide_02,.mod_02,.mod_02 img,.goods_pic").css("width",winWidth);
								if(document.getElementById("slide_02")){
									var scrollContNum=document.getElementById("slide_02").getElementsByTagName("div").length,slide_02 = new ScrollPic();
									slide_02.scrollContId   = "slide_02"; //内容容器ID
									slide_02.dotListId      = "slide_02_dot";//点列表ID
									slide_02.dotOnClassName = "selected";
									slide_02.arrLeftId      = "sl_left"; //左箭头ID
									slide_02.arrRightId     = "sl_right";//右箭头ID
									slide_02.scrollContNum  = scrollContNum;
									slide_02.frameWidth     = winWidth;
									slide_02.pageWidth      = winWidth;
									slide_02.upright        = false;
									slide_02.speed          = 20;
									slide_02.space          = 30;
									slide_02.autoPlayTime   = 3; //秒 
									slide_02.initialize(); //初始化

								}	
								
							}
							
							base.cancelLoading();

				}))().start();
	};
	
	
	//显示商品介绍详情
	exports.loadDetail=function(){
		
		
		$("#ldhGoods .goods_more_info").html(detail);
		
	}
	
	
	
	
	
	
	
    
	var goodsParams={
	};
	
	function count(o){
        var t = typeof o;
        if(t == 'string'){
                return o.length;
        }else if(t == 'object'){
                var n = 0;
                for(var i in o){
                        n++;
                }
                return n/2;
        }
        return false;
   }
	
	//添加商品到购物车
	exports.addCartNum=function(shopId,merchandiseId,price){
		
		
		//goodsParams[0].merchandiseId=merchandiseId;
		//goodsParams[0].nums=1;
		
		$("#"+merchandiseId+" .btn_sub").show();
		
		$("#"+merchandiseId+" span").show();

		$("#"+merchandiseId+" span").html(parseInt($("#"+merchandiseId+" span").text())+1);
		
		$("#ldhGoods .goods_btm em:eq(0)").html(parseInt($("#ldhGoods .goods_btm em:eq(0)").text())+1);
		
		//$("#ldhGoods .goods_btm em:eq(0)").html((Number($("#ldhGoods .goods_btm em:eq(0)").text())+Number(price)).toFixed(2));
		
		
		var length=count(goodsParams);
		if(length==0){
			goodsParams["goods[0].merchandiseId"]=merchandiseId;
			goodsParams["goods[0].nums"]=1;
		}else{
			var n=0,c_n=0,exit=false;
			for(var p in goodsParams){
				
				if(goodsParams[p]==merchandiseId){
					
					exit=true;
					c_n=n;
				}
				n++;
			}
			if(exit){
				c_n=c_n/2;
				goodsParams["goods["+c_n+"].merchandiseId"]=merchandiseId;
				goodsParams["goods["+c_n+"].nums"]=$("#"+merchandiseId+" span").text();
			}else{

				goodsParams["goods["+length+"].merchandiseId"]=merchandiseId;
				goodsParams["goods["+length+"].nums"]=$("#"+merchandiseId+" span").text();
			}
		}
		
		for(var p in goodsParams){
			
			//alert(p+":"+goodsParams[p]);
		}
	
		
	};
	
	
	//在购物车删除商品
	exports.subCartNum=function(merchandiseId,price){
		
		$("#"+merchandiseId+" span").html(parseInt($("#"+merchandiseId+" span").text())-1);

		if($("#"+merchandiseId+" span").text()=="0"){
			$("#"+merchandiseId+" .btn_sub").hide();
			$("#"+merchandiseId+" span").hide();
			
		}
		
		$("#ldhGoods .goods_btm em:eq(0)").html(parseInt($("#ldhGoods .goods_btm em:eq(0)").text())-1);
		
		//$("#ldhStore .store_goods_btm em:eq(0)").html((Number($("#ldhStore .store_goods_btm em:eq(0)").text())-Number(price)).toFixed(2));
		
		
	
			var n=0,c_n=0,isDelete=false;
			
			for(var p in goodsParams){
				
				if(goodsParams[p]==merchandiseId){
					
					if($("#"+merchandiseId+" span").text()=="0"){
						
						
						isDelete=true;
					}
					
					c_n=n;
				}
				n++;
			}
			c_n=c_n/2;
			//当num=0时，这个属性已经删除了。所以不需要重新赋值
			if(!isDelete){
				goodsParams["goods["+c_n+"].merchandiseId"]=merchandiseId;
				goodsParams["goods["+c_n+"].nums"]=$("#"+merchandiseId+" span").text();
			}else{
				delete goodsParams["goods["+c_n+"].merchandiseId"];
				delete goodsParams["goods["+c_n+"].nums"];
			}
			var _goodsParams={};
			var d_n=0,d_c_n=0;
			for(var p in goodsParams){
				
				if(d_n%2==0){
					
					_goodsParams["goods["+d_c_n+"].merchandiseId"]=goodsParams[p];

				}else{
					_goodsParams["goods["+d_c_n+"].nums"]=goodsParams[p];
					d_c_n++;
				}
				d_n++;
			}
			
			goodsParams=_goodsParams;
			
			/*for(var p in goodsParams){
				
				alert(p+":"+goodsParams[p]);
			}*/
	};
	
	var clickable=true;
	exports.addCart=function(type){
		
	
		if(count(goodsParams)==0){
			
			showTips("请选择购买数量");	
			return;
		}
		
		if(validate.isNull(base.getCookie("userId"))){
			showTips("请先登录");	
			//base.showDiv("#ldhLogin","","?merchandiseId="+base.getParameter("merchandiseId")+"&fromPage=ldhGoods");
			window.location.href=ctx+"/h5/login.shtml?fromPage=ldhGoods&merchandiseId="+base.getParameter("merchandiseId")+"";
			return;
		}
		
		if(type=="1"){
			var p=Number(minAmount)-(Number($("#price").text())*Number($("#num").text()));
			if(p>0){
				showTips("还差"+p.toFixed(2)+"元起送");
				return;
			}
			
		}
		
		if(!clickable){
			return;
		}
		
		clickable=false;
		
		base.showLoading();
		
		goodsParams["type"]=type;
		goodsParams["userId"]=base.getCookie("userId");
		goodsParams["loginSign"]=$ldh_base.getCookie("loginSign");
		goodsParams["sign"]=MD5($ldh_base.getCookie("loginSign")+$ldh_base.getCookie("userId")+type);
		
		
		eval(
				Wind.compile("async", function() {
		
					var data = $await(async.DDF_AsyncRequest("POST",ctx+"/shopapp/Cart/addshoptoCart.do", goodsParams));
		
							if(data["code"]==1){
								$("#ldhGoods .store_goods_addsub span").html("0");
								$("#ldhGoods .store_goods_addsub span").hide();
								$("#ldhGoods .store_goods_addsub .btn_sub").hide();
								$("#ldhGoods .goods_btm em:eq(0)").html("0");
								goodsParams={};
								
								if(type==0){
									//base.showDiv("#ldhCart");
									window.location.href=ctx+"/h5/cart.shtml";
								}else{
									//立即购买
									var arr_cart_id = new Array();
									for(var i=0;i<data["cartIds"].length;i++){
										
										arr_cart_id.push(data["cartIds"][i]);
									}
									//跳转到结算页面
									//window.location.href="?cartIds="+arr_cart_id.join(",")+"#ldhOrder";
									
									window.location.href=ctx+"/h5/suborder/"+arr_cart_id.join(",")+".shtml";
								}
								
								
								
							}else if(data["code"]=="-4444"){
								
								window.location.href=ctx+"/h5/login.shtml?fromPage=ldhGoods&merchandiseId="+base.getParameter("merchandiseId")+"";
								
							}else{
								
								showTips(data["message"]);	
							}
							
							clickable=true;
							base.cancelLoading();
							
		}))().start();
		
		
	}
	
	
});

